package com.z1.core.springframework;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import net.iharder.Base64;

public class SystemPropertyConfigurer extends PropertyPlaceholderConfigurer {
	
	private Logger logger = Logger.getLogger(this.getClass()); 
	
	private String prefix = null;
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	
	private String encryptPropNames = null;
	public void setEncryptPropNames(String encryptPropNames) {
		this.encryptPropNames = encryptPropNames;
	}

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		
		decodeHandler(props);
		
		prefixHandler(props);
		
		super.processProperties(beanFactoryToProcess, props);
	}
	
	private void decodeHandler(Properties props) {
		if (null != encryptPropNames && null != props) {
			logger.info("load decode property begin");
			for (String propName : encryptPropNames.split(",")) {
				if (propName.trim().equals("")) { continue; }
				String value = props.getProperty(propName);
				if (null == value) { continue; }
				try {
					String logStr = "Spring配置参数" + propName + "解密：" + value;
					value = new String(Base64.decode(value));
					props.put(propName, value);
					logStr += " => " + value;
					logger.debug(logStr);
				}
				catch (Throwable e) {
					logger.error("Spring配置参数" + propName +  "解密失败.", e);
				}
			}
			logger.info("load decode property end");
		}
	}
	
	private void prefixHandler(Properties props) {
		if (null != prefix && null != props) {
			logger.info("load system property begin");
			for (Object keyObj : System.getProperties().keySet()) {
				if (null == keyObj) { continue; }
				String key = keyObj.toString();
				if (key.startsWith(prefix)) {
					String property = System.getProperty(key);
					if (null != property) {
						logger.info(key.substring(prefix.length()) + "=" + property);
						props.put(key.substring(prefix.length()), property);
					}
				}
			}
			logger.info("load system property end");
		}
	}
	
}
